<?php session_start();?>
<?php


set_include_path('../140dev/db');
	
require_once('140dev_config.php');	  
require_once('db_lib.php');

if($_GET['check_login'] == "1"){
	$result_arr = array();

	if($_SESSION['logged'] == TRUE){
		$result_arr["logged"] = true;
		$result_arr["username"] = $_SESSION['username'];
		$result_arr["restaurants"] = $_SESSION['restaurants'];
		$result_arr["username_complete"] = $_SESSION['username_complete'];
		$result_arr["username_email"] = $_SESSION['username_email'];
	}
	
	print json_encode($result_arr, JSON_NUMERIC_CHECK);
}
		
if($_GET['login'] == "1"){
			
	$oDB = new db;
    
	if(!$oDB)
	{
		die('Could not connect: ' . mysql_error());
	}
	
	try{
		$result = $oDB->select("SELECT DS_USER_ID, DS_SALT, DS_PWD, ID_USER, DS_USER_NAME, DS_USER_EMAIL FROM MAST_USERS WHERE LOWER(DS_USER_ID) = TRIM(LOWER('" . $_POST['user_name'] . "'));");
		if($row = mysqli_fetch_row($result)){
			$user_name = $row[0];
			$salt = $row[1];			
			$hash = $row[2];
			$hash2 = hash("sha256",  $_POST['user_password']  . $salt);
			if($hash == $hash2){
				$_SESSION['logged'] = TRUE;
				$_SESSION['username'] = $user_name;
				$_SESSION['id_user'] = $row[3];
				$_SESSION['username_complete'] = $row[4];
				$_SESSION['username_email'] = $row[5];
				$esta = "ok";
			}
			$id_user = $row[3];
		}
		if($esta == "ok"){
			$result = $oDB->select("SELECT T2.ID_RESTAURANT, T2.DS_REST_NAME, T2.DS_REST_ADDRESS FROM MAST_USERS_RESTAURANTS T1 INNER JOIN MAST_RESTAURANTS T2 ON T1.ID_RESTAURANT = T2.ID_RESTAURANT WHERE ID_USER = " . $id_user);
			$result_arr = array();
			while($row = mysqli_fetch_row($result)){
				$result_arr_resto = array();
				$result_arr_resto['id_resto'] = $row[0];
				$result_arr_resto['desc_resto'] = $row[1];	
				$result_arr_resto['address_resto'] = $row[2];				
				array_push($result_arr,$result_arr_resto);	
			}
			$_SESSION['restaurants'] = $result_arr;
		}	
		
		echo $esta;
	}
	catch(Exception $e){
		print $e;
	}	
	
}

if($_GET['unlogin'] == "1"){
	
	session_start();
  	if(isset($_SESSION['logged']))
  		unset($_SESSION['logged']);
	
	if(isset($_SESSION['username']))
  		unset($_SESSION['username']);
  		
  	echo "ok";
}

?>
